package app.keter.portal.exp;

import com.keter.framework.core.util.IOUtil;
import app.keter.portal.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 验证框架的基础功能和一些实验性功能特性的方法
 */
@RestController
@RequestMapping("/public/exp/gzip")
public class ExpGzipController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ExpGzipController.class);

    @Qualifier("httpClientTemplate")
    @Autowired
    private RestTemplate httpClientTemplate;

    @GetMapping("/public/exp/gzipokhttp")
    public String gzipOKHttp() throws IOException {
        HttpEntity entity =  new HttpEntity<>(null, gzipHeader());
        HttpEntity<String> response = restTemplate.exchange(services.getCommon()+"/exp/gzip", HttpMethod.GET, entity, String.class);
        return IOUtil.decompressGzip(response.getBody());
    }

    @GetMapping("/public/exp/gziphttpclient")
    @Deprecated //服务端不对基于HttpClient的请求进行gzip自动压缩
    public String gzipHttpClient() throws IOException {
        HttpEntity entity =  new HttpEntity<>(null, gzipHeader());
        HttpEntity<String> response = httpClientTemplate.exchange(services.getCommon()+"/exp/gzip", HttpMethod.GET, entity, String.class);
        return IOUtil.decompressGzip(response.getBody());
    }

    private HttpHeaders gzipHeader() {
        return gzipHeader(new HttpHeaders());
    }

    private HttpHeaders gzipHeader(HttpHeaders headers) {
        headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
        return headers;
    }
}
